<?php

class Admin_GameController extends Zend_Controller_Action
{
	private $_auth;
	private $_acl;
    private $_memcache;
    public function init(){
        $acl                = new My_Acl();
        $auth               = $acl->checkAllowed($this->_request);
        $this->_auth        = $auth->getIdentity();
        $this->view->auth   = $this->_auth;
        $this->_acl         = $acl;
        $this->view->acl    = $this->_acl;
        
        $memcache = new Memcache;
        $memcache->connect('localhost', MEMCACHE_PORT) or die ("Could not connect");
        $this->_memcache = $memcache;
    }
    public function indexAction(){
        $modelRole = new Admin_Model_Role();
        $roleUser = $modelRole->getDataByUserId($this->_auth['userId'])->toArray();
        $gameList = array();
        foreach($roleUser as $row){
            $gameList = array_merge($gameList, json_decode($row['gameId']));
        }
        $gameList = array_unique($gameList);
        $gameList = '("'.implode('","',$gameList).'")';
                
        $modelGame = new Admin_Model_Game();
        $gameList = $modelGame->getDataByGameList($gameList);
        $this->view->gameList = $gameList;
        
    }
    public function cacheAction(){
        
        //echo '<pre>',print_r(unserialize($this->_memcache->get("listKey_".BASE_URL.'_'.ENV.'_'.$gameId))),'</pre>';exit;
		$gameId = $this->_getParam('id', 0);
        $modelGame = new Admin_Model_Game();
		$gameCheck = $modelGame->getDataByID($gameId)->toArray();
        if($gameCheck){
			$this->view->gameCheck = $gameCheck;
            if(!$this->_memcache->get("listKey_".BASE_URL.'_'.ENV.'_'.$gameId)){
                $this->view->mess = "Chưa có cache cho game ".$gameCheck['gameName']." (".$gameCheck['gameId'].")";
                $this->view->flag = "alert";
                $this->view->cache = "no exit";
            }else{
                $listKey = unserialize($this->_memcache->get("listKey_".BASE_URL.'_'.ENV.'_'.$gameId));
                #echo '<pre>',print_r($listKey),'</pre>';exit;
                if($this->getRequest()->isPost()){
                    $formData = $this->getRequest()->getPost();
                    if($formData){
                        if(isset($formData['resourceId'])){
                            $resourceId = $formData['resourceId'];
                            foreach($resourceId as $row){
                                $l = strpos($row,"/");
                                $str = substr($row,$l+1);
                                $l2 = strpos($str,"/");
                                $delAction = substr($str,$l2+1);
                                $delController = substr($str,0,$l2);
                                #echo "$delController : $delAction";
                                if($this->_memcache->get("listKey_".BASE_URL.'_'.ENV.'_'.$gameId)){
                                    foreach($listKey as $k=>$key){
                                        $check = strpos($key,BASE_URL.'_'.ENV.'_'.$gameCheck['gameId'].'_'.$delController.'_'.$delAction);
                                        if($check){
                                            $this->_memcache->delete($key);
                                            unset($listKey[$k]);
                                            $this->view->mess = "Đã xóa cache!";
                                            $this->view->flag = "success";
                                        }
                                    }
                                }
                                $this->_memcache->replace("listKey_".BASE_URL.'_'.ENV.'_'.$gameId,serialize($listKey));
                            }
                            // ghi log
                            if(file_exists(CONFIG_PATH . '/history.ini')){
                                $configHistory = new Zend_Config_Ini(CONFIG_PATH . '/history.ini', APPLICATION_ENV);
                                
                                $dataHistory['userId']      = $this->_auth['userId'];
                                $dataHistory['time']        = time();
                                $dataHistory['url']         = $this->getRequest()->getRequestUri();
                                $dataHistory['module']      = 'admin';
                                $dataHistory['controller']  = 'game';
                                $dataHistory['action']      = 'cache';
                                $dataHistory['obj']         = 'game';
                                $dataHistory['objField']    = $gameCheck['gameName'];
                                $dataHistory['objId']       = $gameId;
                                $modelHistory = new Admin_Model_History();
                                $modelHistory->addData($dataHistory);
                            }
                        }else{
                            $this->view->mess = "Vui lòng chọn chức năng sẽ  xóa cache!";
                            $this->view->flag = "alert";
                        }
                    }else{
                        $this->view->mess = "Vui lòng chọn chức năng sẽ  xóa cache!";
                        $this->view->flag = "alert";
                    }
                }
            }
            $resourceList = $this->_acl->listAllowed($this->_auth);
            $this->view->resourceList = $resourceList;
        }else{
            $this->_helper->redirector('index', 'game', 'admin');
        }
    }
    public function deleteAction(){
        if($this->getRequest()->isPost()){
            $del = $this->getRequest()->getPost('del');
            if($del == 'Có'){
                $gameId = $this->getRequest()->getPost('gameId');
                $modelGame = new Admin_Model_Game();
                $gameCheck = $modelGame->getDataById($gameId);
                $modelGame->deleteData($gameId);
                // ghi log
                if(file_exists(CONFIG_PATH . '/history.ini')){
                    $configHistory = new Zend_Config_Ini(CONFIG_PATH . '/history.ini', APPLICATION_ENV);
                    
                    $dataHistory['userId']      = $this->_auth['userId'];
                    $dataHistory['time']        = time();
                    $dataHistory['url']         = $this->getRequest()->getRequestUri();
                    $dataHistory['module']      = 'admin';
                    $dataHistory['controller']  = 'game';
                    $dataHistory['action']      = 'delete';
                    $dataHistory['obj']         = 'game';
                    $dataHistory['objField']    = $gameCheck['gameName'];
                    $dataHistory['objId']       = $gameId;
                    $modelHistory = new Admin_Model_History();
                    $modelHistory->addData($dataHistory);
                }
            }
            $this->_helper->redirector('index', 'game', 'admin');
        }else{
            $id = $this->_getParam('id', 0);
            $modelGame = new Admin_Model_Game();
            $this->view->gameCheck = $modelGame->getDataById($id);
        }
    }
    public function addAction(){
        $form = new Admin_Form_Game();
        $form->submit->setLabel('Thêm mới');
        $this->view->form = $form;
        
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
                $gameId     = $form->getValue('gameId');
                $catId      = $form->getValue('catId');
                $openDate   = $form->getValue('openDate');
                $gameName   = $form->getValue('gameName');
                $level      = $form->getValue('level');
                $status     = $form->getValue('status');
                //$gameConfig = $form->getValue('gameConfig');
                
                $upload = new Zend_File_Transfer;
                $upload->setDestination(PUBLIC_PATH.'/assets/');
                $files = $upload->getFileInfo();
                $upload->addFilter('Rename', date("Y-m-d-H-i-s-").$upload->getFileName(null,false));
                $upload->receive();
                if($upload->getFileName(null,false)){
                    $gameImg = '/assets/'.$upload->getFileName(null,false);
                }else{
                    $gameImg = '';
                }
                $modelGame = new Admin_Model_Game();
				$gameId = $modelGame->addData($gameId, $gameName, $catId, $gameImg, $this->_helper->time->dateToData($openDate), $this->_auth['userId'],date("Y-m-d"), $level, $status);
                if($gameId){
                    //$file = fopen(CONFIG_PATH.'/'.$gameId.'.ini', 'w'); 
                    //fwrite($file, $gameConfig);
                    //fclose($file);
                    // ghi log
                    if(file_exists(CONFIG_PATH . '/history.ini')){
                        $configHistory = new Zend_Config_Ini(CONFIG_PATH . '/history.ini', APPLICATION_ENV);
                        
                        $dataHistory['userId']      = $this->_auth['userId'];
                        $dataHistory['time']        = time();
                        $dataHistory['url']         = $this->getRequest()->getRequestUri();
                        $dataHistory['module']      = 'admin';
                        $dataHistory['controller']  = 'game';
                        $dataHistory['action']      = 'add';
                        $dataHistory['obj']         = 'game';
                        $dataHistory['objField']    = $gameName;
                        $dataHistory['objId']       = $gameId;
                        $modelHistory = new Admin_Model_History();
                        $modelHistory->addData($dataHistory);
                    }
                }
                        
                $this->_helper->redirector('index', 'game', 'admin');

            }else{
                $form->populate($formData);
            }
        }
    }
    public function editAction(){
		$form = new Admin_Form_Game();
		$form->submit->setLabel('Lưu');
		$this->view->form = $form;
		$id = $this->_getParam('id', 0);
		if($this->getRequest()->isPost()){
			$formData = $this->getRequest()->getPost();            
			if($form->isValid($formData)){
                $modelGame = new Admin_Model_Game();
    			$gameCheck = $modelGame->getDataByID($id);
                    
                $dataUpdate['gameId']     = $form->getValue('gameId');
                $dataUpdate['catId']      = $form->getValue('catId');
                $dataUpdate['openDate']   = $this->_helper->time->dateToData($form->getValue('openDate'));
                $dataUpdate['gameName']   = $form->getValue('gameName');
                $dataUpdate['level']      = $form->getValue('level');
                $dataUpdate['status']     = $form->getValue('status');
                //$dataUpdate['gameConfig'] = $form->getValue('gameConfig');
                
                $dataUpdate['repair']     = json_encode($this->_getParam('resourceId'));

                $upload = new Zend_File_Transfer;
                $upload->setDestination(PUBLIC_PATH.'/assets/');
                $files = $upload->getFileInfo();
                $upload->addFilter('Rename', date("Y-m-d-H-i-s-").$upload->getFileName(null,false));
                $upload->receive();
                if($upload->getFileName(null,false)){
                    $gameImg = '/assets/'.$upload->getFileName(null,false);
                    unlink(ROOT_PATH."/public".$gameCheck['gameImg']);
                }else{
                    $gameImg = $gameCheck['gameImg'];
                }
                $modelGame = new Admin_Model_Game();
                $gameCheck = $modelGame->getDataByGameName($dataUpdate['gameName']);
                
                if(!$gameCheck || $gameCheck['gameId'] == $dataUpdate['gameId']){
                    $modelGame->updateData($id, $dataUpdate['gameName'], $dataUpdate['catId'], $gameImg, $dataUpdate['openDate'], $dataUpdate['repair'], $dataUpdate['level'], $dataUpdate['status']);
                    if($dataUpdate['gameId']){
                        //$file = fopen(CONFIG_PATH.'/'.$dataUpdate['gameId'].'.ini', 'w'); 
                        //fwrite($file, $dataUpdate['gameConfig']);
                        //fclose($file);
                        // ghi log
                        if(file_exists(CONFIG_PATH . '/history.ini')){
                            $configHistory = new Zend_Config_Ini(CONFIG_PATH . '/history.ini', APPLICATION_ENV);
                            
                            $dataHistory['userId']      = $this->_auth['userId'];
                            $dataHistory['time']        = time();
                            $dataHistory['url']         = $this->getRequest()->getRequestUri();
                            $dataHistory['module']      = 'admin';
                            $dataHistory['controller']  = 'game';
                            $dataHistory['action']      = 'edit';
                            $dataHistory['obj']         = 'game';
                            $dataHistory['objField']    = $dataUpdate['gameName'];
                            $dataHistory['objId']       = $dataUpdate['gameId'];
                            $dataHistory['valueField']  = array();
                            $dataHistory['valueOld']    = array();
                            $dataHistory['valueNew']    = array();
                            foreach($dataUpdate as $key=>$value){
                                if(isset($gameCheck[$key]) && $value != $gameCheck[$key]){
                                    $dataHistory['valueField'][] = $key;
                                    $dataHistory['valueOld'][] = $gameCheck[$key];
                                    $dataHistory['valueNew'][] = $value;
                                }
                            }
                            if($dataHistory['valueField']){
                                $dataHistory['valueField']  = json_encode($dataHistory['valueField']);
                                $dataHistory['valueOld']    = json_encode($dataHistory['valueOld']);
                                $dataHistory['valueNew']    = json_encode($dataHistory['valueNew']);
                                $modelHistory = new Admin_Model_History();
                                $modelHistory->addData($dataHistory);
                            }
                        }
                    }
                    $this->_helper->redirector('index', 'game', 'admin');
                }else{
                    $this->view->mess ="Tên game đã tồn tại!!!";
                    $this->view->flag = "alert";
    				$form->populate($formData);
    			}
			}else{
				$form->populate($formData);
			}
		}else{
            $modelGame = new Admin_Model_Game();
			$gameCheck = $modelGame->getDataByID($id)->toArray();
            if($gameCheck){
                if(file_exists(CONFIG_PATH.'/'.$gameCheck['gameId'].'.ini')){
                    $gameCheck['gameConfig'] = file_get_contents(CONFIG_PATH.'/'.$gameCheck['gameId'].'.ini');
                }
                
    			$this->view->gameCheck = $gameCheck;
                if(isset($gameCheck['openDate'])){
                    $gameCheck['openDate'] = $this->_helper->time->dataToDate($gameCheck['openDate']);
                }
    			$form->populate($gameCheck);
                                
                $modelResource  = new Admin_Model_Resource();
                $resourceList   = $modelResource->getAllData();
                $this->view->resourceList = $resourceList;
            }else{
                $this->_helper->redirector('index', 'game', 'admin');
            }
		}
    }
    public function emailAction(){
        $gameId         = $this->_getParam('id', 0);
        $myKpi      = new My_Service_Kpi();
        $modelGame  = new Admin_Model_Game();
        $gameCheck  = $modelGame->getDataByID($gameId)->toArray();
        if($gameCheck){
            $config = new Zend_Config_Ini(CONFIG_PATH . '/'.$gameCheck['gameId'].'.ini', APPLICATION_ENV);
            if(isset($config->sendEmail->status) && $config->sendEmail->status != 1){
                $this->view->flag = "alert";
                $this->view->mess = "Chức năng gửi mail game {$gameCheck['gameId']} đang tạm khóa";
                return;
            }
            #echo '<pre>',print_r($config),'</pre>';
            if($config->email){
                $configEmail = $config->email->toArray();
                #echo '<br />',$gameCheck['gameId'],'<br /><pre>',print_r($configEmail),'</pre>';
                $emailList = array();
                foreach($configEmail as $email){
                    $emailList[] = $email['value'];
                }
                
                if(isset($config->sendEmail->cc) && is_array($config->sendEmail->cc->toArray())){
                    $configEmailCC = $config->sendEmail->cc->toArray();
                    $emailCCList = array();
                    foreach($configEmailCC as $email){
                        $emailCCList[] = $email['value'];
                    }
                }
                
                if(isset($config->sendEmail->bcc) && is_array($config->sendEmail->bcc->toArray())){
                    $configEmailBCC = $config->sendEmail->bcc->toArray();
                    $emailBCCList = array();
                    foreach($configEmailBCC as $email){
                        $emailBCCList[] = $email['value'];
                    }
                }
                #echo '<br /><pre>',print_r($emailList),'</pre>';exit;
                
                $date = $this->_helper->time->addDate(date("Y-m-d"), -1);
		        $date = $this->_getParam('date', $date);
                
                $channels       = $config->channel->toArray();
                $countChannel = count($channels);
                #echo '<pre>',print_r($channels),'</pre>';exit;
                
                $configApplication      = $config->applications->toArray();
                $conn                   = new My_Service_Soap();
                $service                = $conn->getClient($config->applications);
                #echo '<pre>',print_r($service),'</pre>';
                #echo '<pre>',$configApplication['function'],'</pre>';
                if(isset($config->group->kpi->server)){
                    $serverList = array();
                    foreach($config->group->kpi->server as $key=>$value){
                        $serverList[] = $key;
                    }
                    $serverList = implode(',',$serverList);
                }
                if(isset($serverList)){
                    $configApplication['serverList'] = $serverList;
                }
                
                $configData     = $config->applications->toArray();
                $configApplication['date']['value']    = $date;
                $kpi = $config->kpi->toArray();
                #echo '<pre>',print_r($kpi),'</pre>';exit;

                if(isset($kpi['PCU']['index']) && isset($kpi['PCU7']['index']) && isset($kpi['PCU30']['index']) && isset($kpi['ACU']['index']) && isset($kpi['ACU7']['index']) && isset($kpi['ACU30']['index'])){
                    $arrAPI0 = array(
                                    'PCU'       => array('name'=>'PCU - IP','api'=>$kpi['PCU']['index'], 'definition'=>$kpi['PCU']['definition']),
                                    'PCU7'      => array('name'=>'PCU - IP 7','api'=>$kpi['PCU7']['index'], 'definition'=>$kpi['PCU7']['definition']),
                                    'PCU30'     => array('name'=>'PCU - IP 30','api'=>$kpi['PCU30']['index'], 'definition'=>$kpi['PCU30']['definition']),
                                    'ACU'       => array('name'=>'ACU - IP','api'=>$kpi['ACU']['index'], 'definition'=>$kpi['ACU']['definition']),
                                    'ACU7'      => array('name'=>'ACU - IP 7','api'=>$kpi['ACU7']['index'], 'definition'=>$kpi['ACU7']['definition']),
                                    'ACU30'     => array('name'=>'ACU - IP 30','api'=>$kpi['ACU30']['index'], 'definition'=>$kpi['ACU30']['definition']),
                                );
                }
                if(isset($kpi['RegisteredRole']['index'])){
                    $arrAPI0['RegisteredRole']      = array('name'=>'New registered role','api'=>$kpi['RegisteredRole']['index'], 'definition'=>$kpi['RegisteredRole']['definition']);
                }
                if(isset($kpi['RegisteredRole7']['index'])){
                    $arrAPI0['RegisteredRole7']      = array('name'=>'New registered role 7','api'=>$kpi['RegisteredRole7']['index'], 'definition'=>$kpi['RegisteredRole7']['definition']);
                }
                if(isset($kpi['RegisteredRole30']['index'])){
                    $arrAPI0['RegisteredRole30']      = array('name'=>'New registered role 30','api'=>$kpi['RegisteredRole30']['index'], 'definition'=>$kpi['RegisteredRole30']['definition']);
                }
                if(isset($kpi['ActiveRole']['index'])){
                    $arrAPI0['ActiveRole']      = array('name'=>'Active role','api'=>$kpi['ActiveRole']['index'], 'definition'=>$kpi['ActiveRole']['definition']);
                }
                if(isset($kpi['ActiveRole7']['index'])){
                    $arrAPI0['ActiveRole7']      = array('name'=>'Active role 7','api'=>$kpi['ActiveRole7']['index'], 'definition'=>$kpi['ActiveRole7']['definition']);
                }
                if(isset($kpi['ActiveRole30']['index'])){
                    $arrAPI0['ActiveRole30']      = array('name'=>'Active role 30','api'=>$kpi['ActiveRole30']['index'], 'definition'=>$kpi['ActiveRole30']['definition']);
                }
                if(isset($kpi['channel']['PCU']['getFromServer'])){
                    foreach($kpi['channel'] as $key=>$value){
                        if(isset($value['index'])){
                            if($key == "PCU" || 
                                $key == "PCU7" ||
                                $key == "PCU30" ||
                                $key == "ACU" ||
                                $key == "ACU7" ||
                                $key == "ACU30" ||
                                $key == "RegisteredRole" ||
                                $key == "RegisteredRole7" ||
                                $key == "RegisteredRole30" ||
                                $key == "ActiveRole" ||
                                $key == "ActiveRole7" ||
                                $key == "ActiveRole30"){
                                $arrAPI0Channel[$key] = array('name'=>$key,'api'=>$value['index']);
                            }
                        }
                    }
                    if(isset($arrAPI0Channel))
                        $this->view->arrAPI0Channel    = $arrAPI0Channel;
                }
                $arrAPI1 = array();
                if(isset($kpi['TotalUsers']['index']) && isset($kpi['NewRegisteredUsers']['index']) && isset($kpi['NewRegisteredUsers7']['index']) && isset($kpi['NewRegisteredUsers30']['index'])){
                    $arrAPI1 = array(
                                    'TotalUsers'     => array('name'=>'Total registered user','api'=>$kpi['TotalUsers']['index'], 'definition'=>$kpi['TotalUsers']['definition']),
                                    'NewRegisteredUsers'       => array('name'=>'New registered user','api'=>$kpi['NewRegisteredUsers']['index'], 'definition'=>$kpi['NewRegisteredUsers']['definition']),
                                    'NewRegisteredUsers7'      => array('name'=>'New registered user 7','api'=>$kpi['NewRegisteredUsers7']['index'], 'definition'=>$kpi['NewRegisteredUsers7']['definition']),
                                    'NewRegisteredUsers30'     => array('name'=>'New registered user 30','api'=>$kpi['NewRegisteredUsers30']['index'], 'definition'=>$kpi['NewRegisteredUsers30']['definition']),
                                );
                }
                if(isset($kpi['ActiveUsers']['index']) && isset($kpi['ActiveUsers30']['index'])){
                    $arrAPI1['ActiveUsers']      = array('name'=>'Active user (A1)','api'=>$kpi['ActiveUsers']['index'], 'definition'=>$kpi['ActiveUsers']['definition']);
                    $arrAPI1['ActiveUsers30']     = array('name'=>'Active user (A30)','api'=>$kpi['ActiveUsers30']['index'], 'definition'=>$kpi['ActiveUsers30']['definition']);
                }
                if(isset($kpi['TotalLogin']['index'])){
                    $arrAPI1['TotalLogin']      = array('name'=>'Total Login','api'=>$kpi['TotalLogin']['index'], 'definition'=>$kpi['TotalLogin']['definition']);
                }
                
                if(isset($kpi['ConvertedUsers']['index']) && isset($kpi['NewConvertedUsers']['index']) && isset($kpi['ReconvertedUsers']['index']) && isset($kpi['GrossRevenue']['index'])){
                    $arrAPI2 = array(
                                    'ConvertedUsers'      => array('name'=>'Total convert users','api'=>$kpi['ConvertedUsers']['index'], 'definition'=>$kpi['ConvertedUsers']['definition']),
                                    'ConvertedUsers7'     => array('name'=>'Total convert users 7','api'=>$kpi['ConvertedUsers7']['index'], 'definition'=>$kpi['ConvertedUsers7']['definition']),
                                    'ConvertedUsers30'    => array('name'=>'Total convert users 30','api'=>$kpi['ConvertedUsers30']['index'], 'definition'=>$kpi['ConvertedUsers30']['definition']),
                                    'NewConvertedUsers'        => array('name'=>'New convert users','api'=>$kpi['NewConvertedUsers']['index'], 'definition'=>$kpi['NewConvertedUsers']['definition']),
                                    'ReconvertedUsers'         => array('name'=>'Re-convert users','api'=>$kpi['ReconvertedUsers']['index'], 'definition'=>$kpi['ReconvertedUsers']['definition']),
                                    'GrossRevenue'      => array('name'=>'Gross Revenue (VNĐ)','api'=>$kpi['GrossRevenue']['index'], 'definition'=>$kpi['GrossRevenue']['definition']),
                                ); 
                }
                $arrAPI3 = array();
                $arrAPI4 = array();
                if(isset($config->api->ssgroup) && $config->api->ssgroup == 1){
                    foreach($kpi as $key=>$value){
                        if(isset($value['index']) && isset($value['definition'])){
                            if($key == "getTotalPassports" || 
                                $key == "getNewRegisteredPassports" ||
                                $key == "getNewRegisteredPassports30" ||
                                $key == "getFirstLogin" ||
                                $key == "getFirstLogin30" ||
                                $key == "getActiveUsers" ||
                                $key == "getActiveUsers30" ||
                                $key == "getChurnAccounts30"){
                                $arrAPI3[$key] = array('name'=>$value['definition'],'api'=>$value['index'], 'definition'=>$value['definition']);
                            }else{
                                $arrAPI4[$key] = array('name'=>$value['definition'],'api'=>$value['index'], 'definition'=>$value['definition']);
                            }
                        }
                    }
                }
                                
                            
                $urlModule      = "default";
                $urlController  = "kpi";
                $urlAction      = "index";
                $memcache = new Memcache;
                $memcache->connect('localhost', MEMCACHE_PORT) or die ("Could not connect");
                $this->_memcache = $memcache;
                $_my_mem = new My_Mem();
                $this->_my_mem = $_my_mem;
                
                
                if(isset($arrAPI0) && $arrAPI0){
                    #$this->_memcache->delete($keyMem);
                    $data0 = array();
                    foreach($arrAPI0 as $key=>$API){
                        $configApplication['index']                 = $API['api'];
                        $keyMem = 'mc_'.BASE_URL.'_'.ENV.'_'.$gameCheck['gameId'].'_'.$urlController.'_'.$urlAction.'_'.$date.'_'.$configApplication['index'];
                        if($this->_memcache->get($keyMem) && in_array($urlModule.'/'.$urlController,$config->cache->controller->toArray())){
                            $data0[$key] = $this->_my_mem->get($keyMem, $config->cache->time);
                        }else{
                            $params                                     = $conn->{$configApplication['prepareParams2']}($configApplication);
                            #echo '<pre>',print_r($params),'</pre><br />';
                            try{
                                $data0[$key] = $service->{$configApplication['function']}($params);
                                if(isset($data0[$key]['status']) && $data0[$key]['status'] != 1){
                                    $data0[$key]['result'] = 0;
                                }else{
                                    if($myKpi->checkCreatCache($date))
                                        $this->_my_mem->set($keyMem,serialize($data0[$key]),false,$config->cache->time);
                                }
                                #echo '<pre>',print_r($data0[$key]),'</pre><br />';
                            }catch(Exception $ex){
                    
                            }
                        }
                    }
                    #exit;
                }
                if(isset($arrAPI0Channel) && $arrAPI0Channel){
                    $kpiPCUChannelAllow = array();
                    if(isset($config->kpi->channel->allow)){
                        $kpiPCUChannelAllow = $config->kpi->channel->allow->toArray();
                    }
                    if(isset($config->clusters) || isset($config->ccu->clusters)){
                        if(isset($config->ccu->clusters)){
                            $clusters = $config->ccu->clusters->toArray();
                        }else{
                            $clusters = $config->clusters->toArray();
                        }
                    }
                    if(is_array($clusters) && $clusters){
                        $serverCCCUList = array();
                        foreach($clusters as $row){
                            if(isset($row['value']) && is_array($row['value']) && $row['value']){
                                $serverCCCUList = array_merge($serverCCCUList,$row['value']);
                            }
                        }
                    }
                    foreach($channels as $key=>$value){
                        $channelsServerList[$key] = array();
                        if(!isset($value['value'])){
                            continue;
                        }
                        foreach($value['value'] as $row){
                            if(!in_array($row,$serverCCCUList)){
                                continue;
                            }     
                            $channelsServerList[$key][] = $row;
                        }
                    }
                    $data0Channel = array();
                    foreach($arrAPI0Channel as $key=>$API){
                        foreach($channels as $key2=>$channel){
                            if(!in_array($key2, $kpiPCUChannelAllow)){
                                continue;
                            }
                            $serverList = implode(',',$channelsServerList[$key2]);
                            $configApplication['serverList'] = $serverList;
                            
                            if(isset($kpi['channel'][$key][$key2]['index'])){
                                $configApplication['index']                 = $kpi['channel'][$key][$key2]['index'];
                            }else{
                                $configApplication['index']                 = $API['api'];
                            }
                            if(isset($kpi['channel'][$key][$key2]['channel'])){
                                $configApplication['channelingAgentId']     = $kpi['channel'][$key][$key2]['channel'];
                            }else{
                                $configApplication['channelingAgentId']     = $key2;
                            }
                            $keyMem = 'mc_'.BASE_URL.'_'.ENV.'_'.$gameId.'_'.$urlController.'_'.$urlAction.'_'.$date.'_'.$configApplication['index'].'_'.$configApplication['channelingAgentId'];
                            if($this->_memcache->get($keyMem) && in_array($urlModule.'/'.$urlController,$config->cache->controller->toArray())){
                                $data0Channel[$key][$key2] = $this->_my_mem->get($keyMem, $config->cache->time);
                            }else{
                                $params                                         = $conn->{$configApplication['prepareParams2']}($configApplication);
                                #echo '<pre>',print_r($params),'</pre><br />';
                                try{
                                    $data0Channel[$key][$key2] = $service->{$configApplication['function']}($params);
                                    #echo '<pre>',print_r($data0Channel),'</pre><br />';
                                    if(isset($data0Channel[$key][$key2]['status']) && $data0Channel[$key][$key2]['status'] != 1){
                                        $data0Channel[$key][$key2]['result'] = 0;
                                    }else{
                                        if($myKpi->checkCreatCache($date))
                                            $this->_my_mem->set($keyMem,serialize($data0Channel[$key][$key2]),false,$config->cache->time);
                                    }
                                }catch(Exception $ex){
                        
                                }
                            }
                        }
                    }
                    #exit;
                }
                if(isset($arrAPI1) && $arrAPI1){
                    #$this->_memcache->delete($keyMem);
                    $data1 = array();
                    foreach($arrAPI1 as $key=>$API){
                        foreach($channels as $key2=>$channel){
                            if(isset($kpi[$key][$key2]['index'])){
                                $configApplication['index']                 = $kpi[$key][$key2]['index'];
                            }else{
                                $configApplication['index']                 = $API['api'];
                            }
                            if(isset($kpi[$key][$key2]['channel'])){
                                $configApplication['channelingAgentId']     = $kpi[$key][$key2]['channel'];
                            }else{
                                $configApplication['channelingAgentId']     = $key2;
                            }
                            $keyMem = 'mc_'.BASE_URL.'_'.ENV.'_'.$gameCheck['gameId'].'_'.$urlController.'_'.$urlAction.'_'.$date.'_'.$configApplication['index'].'_'.$configApplication['channelingAgentId'];
                            if($this->_memcache->get($keyMem) && in_array($urlModule.'/'.$urlController,$config->cache->controller->toArray())){
                                $data1[$key][$key2] = $this->_my_mem->get($keyMem, $config->cache->time);
                            }else{
                                $params                                         = $conn->{$configApplication['prepareParams2']}($configApplication);
                                #echo '<pre>',print_r($params),'</pre><br />';
                                try{
                                    $data1[$key][$key2] = $service->{$configApplication['function']}($params);
                                    if(isset($data1[$key][$key2]['status']) && $data1[$key][$key2]['status'] != 1){
                                        $data1[$key][$key2]['result'] = 0;
                                    }else{
                                        if($myKpi->checkCreatCache($date))
                                            $this->_my_mem->set($keyMem,serialize($data1[$key][$key2]),false,$config->cache->time);
                                    }
                                    #echo '<pre>',print_r($data1[$key][$key2]),'</pre><br />';
                                }catch(Exception $ex){
                        
                                }
                            }
                        }
                    }
                    #exit;
                }
                if(isset($arrAPI2) && $arrAPI2){
                    #$this->_memcache->delete($keyMem);
                    $data2 = array();
                    foreach($arrAPI2 as $key=>$API){
                        foreach($channels as $key2=>$channel){
                            if(isset($kpi[$key][$key2]['index'])){
                                $configApplication['index']                 = $kpi[$key][$key2]['index'];
                            }else{
                                $configApplication['index']                 = $API['api'];
                            }
                            if(isset($kpi[$key][$key2]['channel'])){
                                $configApplication['channelingAgentId']     = $kpi[$key][$key2]['channel'];
                            }else{
                                $configApplication['channelingAgentId']     = $key2;
                            }
                            $keyMem = 'mc_'.BASE_URL.'_'.ENV.'_'.$gameCheck['gameId'].'_'.$urlController.'_'.$urlAction.'_'.$date.'_'.$configApplication['index'].'_'.$configApplication['channelingAgentId'];
                            if($this->_memcache->get($keyMem) && in_array($urlModule.'/'.$urlController,$config->cache->controller->toArray())){
                                $data2[$key][$key2] = $this->_my_mem->get($keyMem, $config->cache->time);
                            }else{
                                $params                                         = $conn->{$configApplication['prepareParams2']}($configApplication);
                                #echo '<pre>',print_r($params),'</pre><br />';
                                try{
                                    $data2[$key][$key2] = $service->{$configApplication['function']}($params);
                                    if(isset($data2[$key][$key2]['status']) && $data2[$key][$key2]['status'] != 1){
                                        $data2[$key][$key2]['result'] = 0;
                                    }else{
                                        if($myKpi->checkCreatCache($date))
                                            $this->_my_mem->set($keyMem,serialize($data2[$key][$key2]),false,$config->cache->time);
                                    }
                                    #echo '<pre>',print_r($data2[$key][$key2]),'</pre><br />';
                                }catch(Exception $ex){
                        
                                }
                            }
                        }
                    }
                    #exit;
                }

                if(isset($arrAPI3) && $arrAPI3){
                    foreach($arrAPI3 as $key=>$API){
                        $configApplication['index'] = $API['api'];
                        $keyMem = 'mc_'.BASE_URL.'_'.ENV.'_'.$gameCheck['gameId'].'_'.$urlController.'_'.$urlAction.'_'.$date.'_'.$configApplication['index'];
                        if($this->_memcache->get($keyMem) && in_array($urlModule.'/'.$urlController,$config->cache->controller->toArray())){
                            $data3[$key] = $this->_my_mem->get($keyMem, $config->cache->time);
                        }else{
                            $params = $conn->{$configApplication['prepareParams2']}($configApplication);
                            #echo '<pre>',print_r($params),'</pre><br />';
                            try{
                                $data3[$key] = $service->{$configApplication['function']}($params);
                                if(isset($data3[$key]['status']) && $data3[$key]['status'] != 1){
                                    $data3[$key]['result'] = 0;
                                }else{
                                    if($myKpi->checkCreatCache($date))
                                        $this->_my_mem->set($keyMem,serialize($data3[$key]),false,$config->cache->time);
                                }
                                #echo '<pre>',print_r($data3[$key]),'</pre><br />';
                            }catch(Exception $ex){
                    
                            }
                        }
                    }
                    #exit;
                }

                if(isset($arrAPI4) && $arrAPI4){
                    foreach($arrAPI4 as $key=>$API){
                        $configApplication['index'] = $API['api'];
                        $keyMem = 'mc_'.BASE_URL.'_'.ENV.'_'.$gameCheck['gameId'].'_'.$urlController.'_'.$urlAction.'_'.$date.'_'.$configApplication['index'];
                        if($this->_memcache->get($keyMem) && in_array($urlModule.'/'.$urlController,$config->cache->controller->toArray())){
                            $data4[$key] = $this->_my_mem->get($keyMem, $config->cache->time);
                        }else{
                            $params                                     = $conn->{$configApplication['prepareParams2']}($configApplication);
                            #echo '<pre>',print_r($params),'</pre><br />';
                            try{
                                $data4[$key] = $service->{$configApplication['function']}($params);
                                if(isset($data4[$key]['status']) && $data4[$key]['status'] != 1){
                                    $data4[$key]['result'] = 0;
                                }else{
                                    if($myKpi->checkCreatCache($date))
                                        $this->_my_mem->set($keyMem,serialize($data4[$key]),false,$config->cache->time);
                                }
                                #echo '<pre>',print_r($data4[$key]),'</pre><br />';
                            }catch(Exception $ex){
                    
                            }
                        }
                    }
                    #exit;
                }
                
                
                $content = '';
                if(isset($config->sendEmail->top)){
                    $content .= $config->sendEmail->top."<br />";
                }
                
                $content .= 'KPI report game '.$gameCheck['gameName'].' ('.$gameCheck['gameId'].') ngày '. $this->_helper->time->dataToDate($date).'. <br /><br /><br />';
                
                $content .= '
                        <table border="0" cellspacing="0" cellpadding="5" style="width: 100%; border-top: 1px solid #9A0000;border-left: 1px solid #d4d4d4;">';
                if((isset($arrAPI0) && $arrAPI0) || (isset($arrAPI1) && $arrAPI1)){
                    $content .= '
                                <thead>
                                    <tr>
                                        <td style="border-right: 1px solid #9A0000;border-bottom: 1px solid #9A0000;background: #C20000;color: #ffffff;text-align: center;font-weight: bold;" width="5%">STT</td>
                                        <td style="border-right: 1px solid #9A0000;border-bottom: 1px solid #9A0000;background: #C20000;color: #ffffff;text-align: center;font-weight: bold;" width="15%">KPIs - User</td>
                                        <td style="border-right: 1px solid #9A0000;border-bottom: 1px solid #9A0000;background: #C20000;color: #ffffff;text-align: center;font-weight: bold;" width="40%">Definition</td>
                                ';
                                if($countChannel > 1){
                                    $content .= '                    
                                                    <td style="border-right: 1px solid #9A0000;border-bottom: 1px solid #9A0000;background: #C20000;color: #ffffff;text-align: center;font-weight: bold;">Total</td>
                                            ';
                                }                        
                                foreach($channels as $channel){
                                    $content .= '<td style="border-right: 1px solid #9A0000;border-bottom: 1px solid #9A0000;background: #C20000;color: #ffffff;text-align: center;font-weight: bold;">'.$channel['name'].'</td>';
                                }
                                $content .= '
                                                </tr>
                                            </thead>
                                            <tbody>
                                            ';
                                                    $stt    = 1;
                                                    if(isset($arrAPI0)){
                                                        foreach($arrAPI0 as $key=>$API){
                                                            if($key != 'RegisteredRole' && $key != 'ActiveRole'){
                                                                (isset($data0[$key]['result'][$date])) ? $total = number_format($data0[$key]['result'][$date],0,'.',',') : $total = '-';
                                                                $content .= '<tr>';
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: center;">'.$stt.'</td>';
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">'.$API['name'].'</td>';
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">'.$API['definition'].'</td>';
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">'.$total.'</td>';
                                                                if(isset($countChannel) && $countChannel > 1){
                                                                    foreach($channels as $key2=>$channel){
                                                                        if(isset($data0Channel[$key][$key2]['result'][$date]))
                                                                            $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">'.number_format($data0Channel[$key][$key2]['result'][$date],0,'.',',').'</td>';
                                                                        else
                                                                            $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">-</td>';
                                                                    }
                                                                }
                                                                $content .= '</tr>';
                                                                ++$stt;
                                                            }
                                                        }
                                                    }
                                                    if(isset($arrAPI1)){
                                                        $a1     = array();
                                                        $login  = array();
                                                        foreach($arrAPI1 as $key=>$API){
                                                            if($key == 'TotalUsers'){
                                                                $content .= '<tr>';
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: center;">'.$stt.'</td>';
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">'.$API['name'].'</td>';
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">'.$API['definition'].'</td>';
                                                                $total = 0;
                                                                foreach($channels as $key2=>$channel){
                                                                    if(isset($data1[$key][$key2]['status']) && $data1[$key][$key2]['status'] == 1){
                                                                        $total += $data1[$key][$key2]['result'][$date];
                                                                    }
                                                                }
                                                                if($countChannel > 1){
                                                                    if($total){
                                                                        $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">'.number_format($total,0,'.',',').'</td>';
                                                                    }else{
                                                                        $total = 0;
                                                                        $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">-</td>';
                                                                    }
                                                                
                                                                    if($key == 'ActiveUsers'){
                                                                        $a1['total'] = $total;
                                                                    }
                                                                    if($key == 'TotalLogin'){
                                                                        $a1['total'] = $total;
                                                                    }
                                                                }
                                                                
                                                                foreach($channels as $key2=>$channel){
                                                                    if(is_numeric($data1[$key][$key2]['result'][$date]) && $data1[$key][$key2]['result'][$date] > 0){
                                                                        $value = $data1[$key][$key2]['result'][$date];
                                                                        $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">'.number_format($value,0,'.',',').'</td>';
                                                                    }else{
                                                                        $value = 0;
                                                                        $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">-</td>';
                                                                    }
                                                                    if($key == 'ActiveUsers'){
                                                                        $a1[$key2] = $value;
                                                                    }
                                                                    if($key == 'TotalLogin'){
                                                                        $a1[$key2] = $value;
                                                                    }
                                                                }
                                                                $content .= '</tr>';
                                                                ++$stt;
                                                            }
                                                        }
                                                    }
                                                    if(isset($arrAPI0)){
                                                        foreach($arrAPI0 as $key=>$API){
                                                            if($key == 'RegisteredRole'){
                                                                (isset($data0[$key]['result'][$date])) ? $total = number_format($data0[$key]['result'][$date],0,'.',',') : $total = '-';
                                                                $content .= '<tr>';
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: center;">'.$stt.'</td>';
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">'.$API['name'].'</td>';
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">'.$API['definition'].'</td>';
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">'.$total.'</td>';
                                                                if(isset($countChannel) && $countChannel > 1){
                                                                    foreach($channels as $key2=>$channel){
                                                                        if(isset($data0Channel[$key][$key2]['result'][$date]))
                                                                            $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">'.number_format($data0Channel[$key][$key2]['result'][$date],0,'.',',').'</td>';
                                                                        else
                                                                            $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">-</td>';
                                                                    }
                                                                }
                                                                $content .= '</tr>';
                                                                ++$stt;
                                                            }
                                                        }
                                                    }
                                                    if(isset($arrAPI1)){
                                                        $a1     = array();
                                                        $login  = array();
                                                        foreach($arrAPI1 as $key=>$API){
                                                            if($key == 'NewRegisteredUsers' || $key == 'NewRegisteredUsers7' || $key == 'NewRegisteredUsers30'){
                                                                $content .= '<tr>';
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: center;">'.$stt.'</td>';
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">'.$API['name'].'</td>';
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">'.$API['definition'].'</td>';
                                                                $total = 0;
                                                                foreach($channels as $key2=>$channel){
                                                                    if(isset($data1[$key][$key2]['status']) && $data1[$key][$key2]['status'] == 1){
                                                                        $total += $data1[$key][$key2]['result'][$date];
                                                                    }
                                                                }
                                                                if($countChannel > 1){
                                                                    if($total){
                                                                        $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">'.number_format($total,0,'.',',').'</td>';
                                                                    }else{
                                                                        $total = 0;
                                                                        $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">-</td>';
                                                                    }
                                                                
                                                                    if($key == 'ActiveUsers'){
                                                                        $a1['total'] = $total;
                                                                    }
                                                                    if($key == 'TotalLogin'){
                                                                        $a1['total'] = $total;
                                                                    }
                                                                }
                                                                
                                                                foreach($channels as $key2=>$channel){
                                                                    if(is_numeric($data1[$key][$key2]['result'][$date]) && $data1[$key][$key2]['result'][$date] > 0){
                                                                        $value = $data1[$key][$key2]['result'][$date];
                                                                        $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">'.number_format($value,0,'.',',').'</td>';
                                                                    }else{
                                                                        $value = 0;
                                                                        $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">-</td>';
                                                                    }
                                                                    if($key == 'ActiveUsers'){
                                                                        $a1[$key2] = $value;
                                                                    }
                                                                    if($key == 'TotalLogin'){
                                                                        $a1[$key2] = $value;
                                                                    }
                                                                }
                                                                $content .= '</tr>';
                                                                ++$stt;
                                                            }
                                                        }
                                                    }
                                                    if(isset($arrAPI0)){
                                                        foreach($arrAPI0 as $key=>$API){
                                                            if($key == 'ActiveRole'){
                                                                (isset($data0[$key]['result'][$date])) ? $total = number_format($data0[$key]['result'][$date],0,'.',',') : $total = '-';
                                                                $content .= '<tr>';
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: center;">'.$stt.'</td>';
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">'.$API['name'].'</td>';
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">'.$API['definition'].'</td>';
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">'.$total.'</td>';
                                                                if(isset($countChannel) && $countChannel > 1){
                                                                    foreach($channels as $key2=>$channel){
                                                                        if(isset($data0Channel[$key][$key2]['result'][$date]))
                                                                            $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">'.number_format($data0Channel[$key][$key2]['result'][$date],0,'.',',').'</td>';
                                                                        else
                                                                            $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">-</td>';
                                                                    }
                                                                }
                                                                $content .= '</tr>';
                                                                ++$stt;
                                                            }
                                                        }
                                                    }
                                                    if(isset($arrAPI1)){
                                                        $a1     = array();
                                                        $login  = array();
                                                        foreach($arrAPI1 as $key=>$API){
                                                            if($key == 'ActiveUsers' || $key == 'ActiveUsers30' || $key == 'TotalLogin'){
                                                                $content .= '<tr>';
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: center;">'.$stt.'</td>';
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">'.$API['name'].'</td>';
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">'.$API['definition'].'</td>';
                                                                $total = 0;
                                                                foreach($channels as $key2=>$channel){
                                                                    if(isset($data1[$key][$key2]['status']) && $data1[$key][$key2]['status'] == 1){
                                                                        $total += $data1[$key][$key2]['result'][$date];
                                                                    }
                                                                }
                                                                if($countChannel > 1){
                                                                    if($total){
                                                                        $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">'.number_format($total,0,'.',',').'</td>';
                                                                    }else{
                                                                        $total = 0;
                                                                        $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">-</td>';
                                                                    }
                                                                
                                                                    if($key == 'ActiveUsers'){
                                                                        $a1['total'] = $total;
                                                                    }
                                                                    if($key == 'TotalLogin'){
                                                                        $a1['total'] = $total;
                                                                    }
                                                                }
                                                                
                                                                foreach($channels as $key2=>$channel){
                                                                    if(is_numeric($data1[$key][$key2]['result'][$date]) && $data1[$key][$key2]['result'][$date] > 0){
                                                                        $value = $data1[$key][$key2]['result'][$date];
                                                                        $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">'.number_format($value,0,'.',',').'</td>';
                                                                    }else{
                                                                        $value = 0;
                                                                        $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">-</td>';
                                                                    }
                                                                    if($key == 'ActiveUsers'){
                                                                        $a1[$key2] = $value;
                                                                    }
                                                                    if($key == 'TotalLogin'){
                                                                        $a1[$key2] = $value;
                                                                    }
                                                                }
                                                                $content .= '</tr>';
                                                                ++$stt;
                                                            }
                                                        }
                                                    }
                                $content .= '
                                            </tbody>';
                }
                if(isset($arrAPI2) && $arrAPI2){
                    $content .= '
                                <thead>
                                    <tr>
                                        <td style="border-right: 1px solid #9A0000;border-bottom: 1px solid #9A0000;background: #C20000;color: #ffffff;text-align: center;font-weight: bold;">STT</td>
                                        <td style="border-right: 1px solid #9A0000;border-bottom: 1px solid #9A0000;background: #C20000;color: #ffffff;text-align: center;font-weight: bold;">KPIs - Payment</td>
                                        <td style="border-right: 1px solid #9A0000;border-bottom: 1px solid #9A0000;background: #C20000;color: #ffffff;text-align: center;font-weight: bold;">Definition</td>
                                ';
                    
                                if($countChannel > 1){
                                    $content .= '
                                                    <td style="border-right: 1px solid #9A0000;border-bottom: 1px solid #9A0000;background: #C20000;color: #ffffff;text-align: center;font-weight: bold;">Total</td>
                                            ';
                                }
                                foreach($channels as $channel){
                                    $content .= '<td style="border-right: 1px solid #9A0000;border-bottom: 1px solid #9A0000;background: #C20000;color: #ffffff;text-align: center;font-weight: bold;">'.((isset($channel['payment']['name'])) ? $channel['payment']['name'] : $channel['name']).'</td>';
                                }
                                $content .= '
                                                </tr>
                                            </thead>
                                            <tbody>
                                            ';
                                                    if(isset($arrAPI2)){
                                                        $convert    = array();
                                                        $revenue    = array();
                                                        foreach($arrAPI2 as $key=>$API){
                                                            $content .= '<tr>';
                                                            $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: center;">'.$stt.'</td>';
                                                            $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">'.$API['name'].'</td>';
                                                            $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">'.$API['definition'].'</td>';
                                                            $total = 0;
                                                            foreach($channels as $key2=>$channel){
                                                                if(isset($data2[$key][$key2]['status']) && $data2[$key][$key2]['status'] == 1){
                                                                    $total += $data2[$key][$key2]['result'][$date];
                                                                }
                                                            }
                                                            
                                                            if($countChannel > 1){
                                                                if($total){
                                                                    $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">'.number_format($total,0,'.',',').'</td>';
                                                                }else{
                                                                    $total = 0;
                                                                    $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">-</td>';
                                                                }
                                                            
                                                                if($key == 'ConvertedUsers'){
                                                                    $convert['total'] = $total;
                                                                }elseif($key == 'GrossRevenue'){
                                                                    $revenue['total'] = $total;
                                                                }
                                                            }
                                                            foreach($channels as $key2=>$channel){
                                                                if(isset($data2[$key][$key2]['result'][$date]) && is_numeric($data2[$key][$key2]['result'][$date]) && $data2[$key][$key2]['result'][$date] > 0){
                                                                    $value = $data2[$key][$key2]['result'][$date];
                                                                    $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">'.number_format($value,0,'.',',').'</td>';
                                                                }else{
                                                                    $value = 0;
                                                                    $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">-</td>';
                                                                }
                                                                if($key == 'ConvertedUsers'){
                                                                    $convert[$key2] = $value;
                                                                }elseif($key == 'GrossRevenue'){
                                                                    $revenue[$key2] = $value;
                                                                }
                                                            }
                                                            $content .= '</tr>';
                                                            ++$stt;
                                                        }
                                                    }
                                $content .= '
                                                <tr>
                                                    <td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: center;">'.$stt.'</td>
                                                    <td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">Game money created</td>
                                                    <td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">Gross Revenue / rate</td>
                                            ';
                                                        foreach($revenue as $key=>$row){
                                                            if(is_numeric($row) && $row > 0)
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">'.number_format($row/100,0,'.',',').'</td>';
                                                            else
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">-</td>';
                                                        }
                                $content .= '
                                                </tr>
                                            ';
                                if($countChannel > 1){
                                    $content .='
                                                    <tr>
                                                        <td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: center;">'.++$stt.'</td>
                                                        <td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">Game money consumed</td>
                                                        <td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">Total game money was consumed in IB shop</td>
                                                ';
                                                            foreach($revenue as $key=>$row){
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">-</td>';
                                                            }
                                    $content .= '
                                                    </tr>
                                                    <tr>
                                                        <td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: center;">'.++$stt.'</td>
                                                        <td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">Game money remain</td>
                                                        <td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">Total game money remain in all roles</td>
                                                ';
                                                            foreach($revenue as $key=>$row){
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">-</td>';
                                                            }
                                    $content .= '
                                                    </tr>
                                                ';
                                }
                                $content .= '
                                                <tr>
                                                    <td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: center;">'.++$stt.'</td>
                                                    <td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">ARPU (VND)</td>
                                                    <td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">Gross revenue / Total convert users = (18) / (13)</td>
                                            ';
                                                        foreach($revenue as $key=>$row){
                                                            if(isset($revenue[$key]) && $revenue[$key] && isset($convert[$key]) && $convert[$key]) 
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">'.number_format($revenue[$key]/$convert[$key],0,'.',',').'</td>';
                                                            else
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">-</td>';
                                                        }
                                $content .= '
                                                </tr>
                                                <tr>
                                                    <td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: center;">'.++$stt.'</td>
                                                    <td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">Convertion (%)</td>
                                                    <td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">Total convert users / A1 = (13) / (11)</td>
                                            ';
                                                        foreach($convert as $key=>$row){
                                                            if(isset($convert[$key]) && $convert[$key] && isset($a1[$key]) && $a1[$key]) 
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">'.number_format(100*$convert[$key]/$a1[$key],2,'.',',').'</td>';
                                                            else
                                                                $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">-</td>';
                                                        }
                                $content .= '
                                                </tr>
                                            </tbody>';
                }
                if(isset($arrAPI3) && $arrAPI3){
                    $content .= '
                                <thead>
                                    <tr>
                                        <td style="border-right: 1px solid #9A0000;border-bottom: 1px solid #9A0000;background: #C20000;color: #ffffff;text-align: center;font-weight: bold;" width="10%">STT</td>
                                        <td style="border-right: 1px solid #9A0000;border-bottom: 1px solid #9A0000;background: #C20000;color: #ffffff;text-align: center;font-weight: bold;" width="45%">KPIs - Account</td>
                                ';
                                if($countChannel > 1){
                                    $content .= '                    
                                                    <td style="border-right: 1px solid #9A0000;border-bottom: 1px solid #9A0000;background: #C20000;color: #ffffff;text-align: center;font-weight: bold;">Total</td>
                                            ';
                                }                        
                                foreach($channels as $channel){
                                    $content .= '<td style="border-right: 1px solid #9A0000;border-bottom: 1px solid #9A0000;background: #C20000;color: #ffffff;text-align: center;font-weight: bold;">'.$channel['name'].'</td>';
                                }
                                $content .= '
                                                </tr>
                                            </thead>
                                            <tbody>
                                            ';
                                                    $stt    = 1;
                                                    if(isset($arrAPI3)){
                                                        foreach($arrAPI3 as $key=>$API){
                                                            (isset($data3[$key]['result'][$date])) ? $key = number_format($data3[$key]['result'][$date],0,'.',',') : $key = '-';
                                                            $content .= '<tr>';
                                                            $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: center;">'.$stt.'</td>';
                                                            $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;">'.$API['name'].'</td>';
                                                            $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">'.$key.'</td>';
                                                            if(isset($countChannel) && $countChannel > 1){
                                                                foreach($channels as $key2=>$channel){
                                                                    $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">-</td>';
                                                                }
                                                            }
                                                            $content .= '</tr>';
                                                            ++$stt;
                                                        }
                                                    }
                                $content .= '
                                            </tbody>';
                }

                if(isset($arrAPI4) && $arrAPI4){
                    $content .= '
                                <thead>
                                    <tr>
                                        <td style="border-right: 1px solid #9A0000;border-bottom: 1px solid #9A0000;background: #C20000;color: #ffffff;text-align: center;font-weight: bold;" width="10%">STT</td>
                                        <td style="border-right: 1px solid #9A0000;border-bottom: 1px solid #9A0000;background: #C20000;color: #ffffff;text-align: center;font-weight: bold;" width="45%">KPIs - Account</td>
                                ';
                                if($countChannel > 1){
                                    $content .= '                    
                                                    <td style="border-right: 1px solid #9A0000;border-bottom: 1px solid #9A0000;background: #C20000;color: #ffffff;text-align: center;font-weight: bold;">Total</td>
                                            ';
                                }                        
                                foreach($channels as $channel){
                                    $content .= '<td style="border-right: 1px solid #9A0000;border-bottom: 1px solid #9A0000;background: #C20000;color: #ffffff;text-align: center;font-weight: bold;">'.((isset($channel['payment']['name'])) ? $channel['payment']['name'] : $channel['name']).'</td>';
                                }
                                $content .= '
                                                </tr>
                                            </thead>
                                            <tbody>
                                            ';
                                                    $stt    = 1;
                                                    if(isset($arrAPI4)){
                                                        foreach($arrAPI4 as $key=>$API){
                                                            (isset($data4[$key]['result'][$date])) ? $key = number_format($data4[$key]['result'][$date],0,'.',',') : $key = '-';
                                                            $content .= '<tr>';
                                                            $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: center;">'.$stt.'</td>';
                                                            $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;" >'.$API['name'].'</td>';
                                                            $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">'.$key.'</td>';
                                                            if(isset($countChannel) && $countChannel > 1){
                                                                foreach($channels as $key2=>$channel){
                                                                    $content .= '<td style="border-right: 1px solid #d4d4d4;border-bottom: 1px solid #d4d4d4;text-align: right;">-</td>';
                                                                }
                                                            }
                                                            $content .= '</tr>';
                                                            ++$stt;
                                                        }
                                                    }
                                $content .= '
                                            </tbody>';
                }
                $content .= '
                        </table>
                            ';
                            
                if(isset($config->sendEmail->bot)){
                    $content .= "<br />".$config->sendEmail->bot;
                }
                #echo '<h1>KPI report game '.$gameCheck['gameName'].' ('.$gameCheck['gameId'].') ngày '. $this->_helper->time->dataToDate($date).'</h1>';
                echo $content."<br />";
                $email_from = "kpi@ssgroup.com.vn";
                $name_from = "kpi";
    
                $mail = new Zend_Mail('UTF-8');
                $mail->setReplyTo($email_from, $name_from);
                $mail->setFrom($email_from, $name_from);
                
                if(isset($emailList) && is_array($emailList)){
                    foreach($emailList as $value){
                        $mail->addTo($value);
                    }
                    if(isset($emailCCList) && is_array($emailCCList)){
                        foreach($emailCCList as $value){
                            $mail->addCc($value);
                        }
                    }
                    if(isset($emailBCCList) && is_array($emailBCCList)){
                        foreach($emailBCCList as $value){
                            $mail->addBcc($value);
                        }
                    }
                    $mail->setSubject('KPI report game '.$gameCheck['gameName'].' ('.$gameCheck['gameId'].') ngày '.$this->_helper->time->dataToDate($date));
                    $mail->setBodyHtml($content);
                    try{
                        $mail->send();#$mail->send($transport);
                        $this->view->flag = "success";
                        $this->view->mess = "Mail report game {$gameCheck['gameId']} đã được gửi.";
                        // ghi log
                        if(file_exists(CONFIG_PATH . '/history.ini')){
                            $configHistory = new Zend_Config_Ini(CONFIG_PATH . '/history.ini', APPLICATION_ENV);
                            
                            $dataHistory['userId']      = $this->_auth['userId'];
                            $dataHistory['time']        = time();
                            $dataHistory['url']         = $this->getRequest()->getRequestUri();
                            $dataHistory['module']      = 'admin';
                            $dataHistory['controller']  = 'game';
                            $dataHistory['action']      = 'email';
                            $dataHistory['obj']         = 'game';
                            $dataHistory['objField']    = $gameCheck['gameName'];
                            $dataHistory['objId']       = $gameId;
                            $modelHistory = new Admin_Model_History();
                            $modelHistory->addData($dataHistory);
                        }
                    }catch(Zend_Mail_Exception $e){
                        //echo $e->getMessage();
                        $this->view->flag = "alert";
                        $this->view->mess = "Có lỗi khi gửi mail!!!";
                    }
                }else{
                    $this->view->flag = "error";
                    $this->view->mess = "Vui lòng xem lại cấu hình người nhận email!!!";
                }
            }else{
                $this->view->flag = "error";
                $this->view->mess = "Vui lòng xem lại cấu hình gửi email!!!";
            }
        }else{
            $this->view->flag = "error";
            $this->view->mess = "Bạn không được quyền truy cập tính năng này!!!";
        }
    }
}